package org.Yiran.timetale_re.client.gui.base;

import com.mojang.blaze3d.platform.Lighting;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.math.Axis;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.entity.EntityRenderDispatcher;
import net.minecraft.client.renderer.entity.ItemRenderer;
import net.minecraft.client.renderer.texture.OverlayTexture;
import net.minecraft.network.chat.Component;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.ItemNameBlockItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.SpawnEggItem;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.Property;
import net.minecraftforge.client.model.data.ModelData;
import org.jetbrains.annotations.NotNull;

import java.util.Collections;

/**
 * 通用模型查看器屏幕
 * 用于在GUI中显示3D模型，支持物品、实体和作物种子的渲染
 * 支持旋转、缩放和动画效果
 */
public class GenericModelViewerScreen extends Screen {
    
    // ==================== 常量定义 ====================
    
    /** GUI宽度 */
    protected static final int GUI_WIDTH = 200;
    
    /** GUI高度 */
    protected static final int GUI_HEIGHT = 140;
    
    /** 缩放增量 */
    private static final float SCALE_INCREMENT = 0.1f;
    
    /** 最小缩放比例 */
    private static final float MIN_SCALE = 0.5f;
    
    /** 最大缩放比例 */
    private static final float MAX_SCALE = 3.0f;
    
    /** 最大生长阶段数 */
    private static final int MAX_GROWTH_STAGES = 8;
    
    /** 每个阶段持续时间(毫秒) */
    private static final long STAGE_DURATION = 1000;

    // ==================== 实例变量 ====================

    /** 要显示的物品堆 */
    protected final ItemStack itemStack;
    
    /** 物品名称 */
    protected final String itemName;
    
    /** GUI左上角X坐标 */
    protected int guiLeft;
    
    /** GUI左上角Y坐标 */
    protected int guiTop;

    // ==================== 生物蛋相关字段 ====================
    
    /** 是否为生物蛋 */
    private final boolean isSpawnEgg;
    
    /** 用于渲染的实体 */
    private Entity entityForRendering;

    // ==================== 种子相关字段 ====================
    
    /** 是否为种子 */
    private final boolean isSeed;
    
    /** 生长阶段 */
    private int growthStage = 0;
    
    /** 上次阶段变化时间 */
    private long lastStageChange = 0;

    // ==================== 3D模型旋转相关变量 ====================
    
    /** X轴旋转角度 */
    private float rotationX = 0.0f;
    
    /** Y轴旋转角度 */
    private float rotationY = 0.0f;
    
    /** 上次X轴旋转角度 */
    private float lastRotationX = 0.0f;
    
    /** 上次Y轴旋转角度 */
    private float lastRotationY = 0.0f;

    // ==================== 缩放相关变量 ====================
    
    /** 缩放因子 */
    private float scaleFactor = 1.0f;

    // ==================== 鼠标拖拽相关变量 ====================
    
    /** 是否正在拖拽 */
    private boolean isDragging = false;
    
    /** 上次鼠标X坐标 */
    private int lastMouseX = 0;
    
    /** 上次鼠标Y坐标 */
    private int lastMouseY = 0;

    // ==================== 构造函数 ====================

    /**
     * 构造函数
     * @param itemStack 要显示的物品堆
     */
    public GenericModelViewerScreen(ItemStack itemStack) {
        super(Component.translatable("screen.timetale_re.model_viewer"));
        this.itemStack = itemStack.copy();
        this.itemName = itemStack.getHoverName().getString();
        this.isSpawnEgg = itemStack.getItem() instanceof SpawnEggItem;
        this.isSeed = isSeedItem(itemStack);

        // 如果是生物蛋，创建实体用于渲染
        if (this.isSpawnEgg) {
            this.entityForRendering = createEntityForSpawnEgg();
        }
    }

    // ==================== 初始化方法 ====================

    @Override
    protected void init() {
        this.guiLeft = (this.width - GUI_WIDTH) / 2;
        this.guiTop = (this.height - GUI_HEIGHT) / 2;
    }

    // ==================== 关闭处理 ====================

    @Override
    public void onClose() {
        super.onClose();
        if (Minecraft.getInstance().player != null) {
            Minecraft.getInstance().player.playSound(SoundEvents.BOOK_PAGE_TURN);
        }
    }

    // ==================== 渲染方法 ====================

    @Override
    public void render(@NotNull GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTicks) {
        this.renderBackground(guiGraphics);
        super.render(guiGraphics, mouseX, mouseY, partialTicks);

        // 渲染标题
        guiGraphics.drawCenteredString(this.font, this.itemName, this.width / 2, this.guiTop - 30, 0xFFFFFF);

        // 渲染3D模型
        render3DModel(guiGraphics, mouseX, mouseY, partialTicks);
    }

    /**
     * 渲染3D模型
     * @param guiGraphics GUI图形对象
     * @param mouseX 鼠标X坐标
     * @param mouseY 鼠标Y坐标
     * @param partialTicks 部分刻度
     */
    private void render3DModel(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTicks) {
        Lighting.setupForFlatItems();

        PoseStack poseStack = guiGraphics.pose();
        poseStack.pushPose();

        if (isSpawnEgg && entityForRendering != null) {
            // 生物蛋特殊渲染：左侧显示实体，右侧显示蛋
            renderSpawnEggModels(guiGraphics, poseStack);
        } else if (isSeed) {
            // 种子特殊渲染：左侧显示作物，右侧显示种子
            renderSeedModels(guiGraphics, poseStack);
        } else {
            // 普通物品渲染
            renderNormalItem(guiGraphics, poseStack);
        }

        poseStack.popPose();
        RenderSystem.enableDepthTest();
    }

    /**
     * 渲染生物蛋模型
     * @param guiGraphics GUI图形对象
     * @param poseStack 姿态栈
     */
    private void renderSpawnEggModels(GuiGraphics guiGraphics, PoseStack poseStack) {
        Minecraft mc = Minecraft.getInstance();
        int screenWidth = mc.getWindow().getGuiScaledWidth();
        int screenHeight = mc.getWindow().getGuiScaledHeight();

        // 计算实体模型的中心位置（屏幕中心）
        float centerX = screenWidth / 2.0f;
        float centerY = screenHeight / 2.0f;

        // 左侧渲染实体模型（可旋转且可缩放）
        poseStack.pushPose();
        poseStack.translate(centerX, centerY, 100.0f);

        // 先进行缩放和旋转
        poseStack.scale(scaleFactor * 25, -scaleFactor * 30, scaleFactor * 30);
        poseStack.mulPose(Axis.XP.rotationDegrees(rotationX));
        poseStack.mulPose(Axis.YP.rotationDegrees(rotationY));

        // 添加实体中心偏移（根据实体类型可能需要调整）
        poseStack.translate(0.0f, -0.5f, 0.0f);

        MultiBufferSource.BufferSource bufferSource = mc.renderBuffers().bufferSource();
        EntityRenderDispatcher entityRenderer = mc.getEntityRenderDispatcher();
        entityRenderer.render(
                entityForRendering,
                0.0D, 0.0D, 0.0D,
                0.0F, 1.0F,
                poseStack,
                bufferSource,
                15728880
        );
        bufferSource.endBatch();
        poseStack.popPose();

        // 右侧渲染蛋模型（固定位置在实体右侧）
        poseStack.pushPose();
        poseStack.translate(centerX + 100, centerY - 30, 100.0f); // 在实体右侧100像素处

        // 对于物品也进行中心对齐
        PM(poseStack, mc);
    }

    /**
     * 渲染种子模型
     * @param guiGraphics GUI图形对象
     * @param poseStack 姿态栈
     */
    private void renderSeedModels(GuiGraphics guiGraphics, PoseStack poseStack) {
        Minecraft mc = Minecraft.getInstance();
        int screenWidth = mc.getWindow().getGuiScaledWidth();
        int screenHeight = mc.getWindow().getGuiScaledHeight();

        // 更新生长阶段
        updateGrowthStage();

        // 计算作物模型的中心位置（屏幕中心）
        float centerX = screenWidth / 2.0f;
        float centerY = screenHeight / 2.0f;

        // 左侧渲染作物模型（显示当前生长阶段，居中显示）
        poseStack.pushPose();
        poseStack.translate(centerX, centerY, 100.0f);

        // 先进行缩放和旋转
        poseStack.scale(scaleFactor * 30, -scaleFactor * 30, scaleFactor * 30);
        poseStack.mulPose(Axis.XP.rotationDegrees(rotationX));
        poseStack.mulPose(Axis.YP.rotationDegrees(rotationY));

        // 添加方块中心偏移，使方块围绕其中心旋转和缩放
        poseStack.translate(-0.5f, -0.5f, -0.5f);

        // 渲染作物方块模型（根据生长阶段）
        Block cropBlock = getCropBlock();
        if (cropBlock != null) {
            MultiBufferSource.BufferSource bufferSource = mc.renderBuffers().bufferSource();
            // 获取作物方块的默认状态
            BlockState blockState = cropBlock.defaultBlockState();

            // 使用通用方法设置生长阶段
            blockState = getGrowthStageBlockState(blockState, cropBlock);

            // 使用方块渲染器渲染作物方块
            mc.getBlockRenderer().renderSingleBlock(
                    blockState,
                    poseStack,
                    bufferSource,
                    15728880,
                    OverlayTexture.NO_OVERLAY,
                    ModelData.EMPTY,
                    RenderType.cutout()
            );
            bufferSource.endBatch();
        }
        poseStack.popPose();

        // 右侧渲染种子模型（固定位置在作物右侧）
        poseStack.pushPose();
        poseStack.translate(centerX + 100, centerY - 10, 100.0f);

        // 对于种子物品也进行中心对齐
        PM(poseStack, mc);
    }

    /**
     * 渲染普通物品
     * @param guiGraphics GUI图形对象
     * @param poseStack 姿态栈
     */
    private void renderNormalItem(GuiGraphics guiGraphics, PoseStack poseStack) {
        // 移动到屏幕中心
        poseStack.translate(width / 2.0f, height / 2.0f, 100.0f);

        // 应用缩放
        poseStack.scale(scaleFactor * 50, -scaleFactor * 50, scaleFactor * 50);

        // 应用旋转
        poseStack.mulPose(Axis.XP.rotationDegrees(rotationX));
        poseStack.mulPose(Axis.YP.rotationDegrees(rotationY));

        // 渲染物品
        MultiBufferSource.BufferSource bufferSource = Minecraft.getInstance().renderBuffers().bufferSource();
        ItemRenderer itemRenderer = Minecraft.getInstance().getItemRenderer();
        itemRenderer.renderStatic(
                itemStack,
                ItemDisplayContext.GUI,
                15728880,
                OverlayTexture.NO_OVERLAY,
                poseStack,
                bufferSource,
                Minecraft.getInstance().level,
                0
        );
        bufferSource.endBatch();
    }

    /**
     * 渲染物品的辅助方法
     * @param poseStack 姿态栈
     * @param mc Minecraft实例
     */
    private void PM(PoseStack poseStack, Minecraft mc) {
        poseStack.translate(0.5f, 0.5f, 0);
        poseStack.scale(50, -50, 50);
        poseStack.translate(-0.5f, -0.5f, 0);

        MultiBufferSource.BufferSource bufferSource2 = mc.renderBuffers().bufferSource();
        ItemRenderer itemRenderer = mc.getItemRenderer();
        itemRenderer.renderStatic(
                itemStack,
                ItemDisplayContext.GUI,
                15728880,
                OverlayTexture.NO_OVERLAY,
                poseStack,
                bufferSource2,
                mc.level,
                0
        );
        bufferSource2.endBatch();
        poseStack.popPose();
    }

    // ==================== 种子相关方法 ====================

    /**
     * 判断是否为种子物品
     * @param stack 物品堆
     * @return 是否为种子
     */
    private boolean isSeedItem(ItemStack stack) {
        if (stack.getItem() instanceof ItemNameBlockItem blockItem) {
            Block block = blockItem.getBlock();
            BlockState defaultState = block.defaultBlockState();
            return defaultState.getProperties().stream()
                    .anyMatch(property -> property.getName().equals("age") &&
                            property.getValueClass() == Integer.class);
        }
        return false;
    }

    /**
     * 获取作物方块
     * @return 作物方块
     */
    private Block getCropBlock() {
        if (itemStack.getItem() instanceof ItemNameBlockItem blockItem) {
            return blockItem.getBlock();
        }
        return Blocks.WHEAT;
    }

    /**
     * 获取生长阶段的方块状态
     * @param blockState 方块状态
     * @param cropBlock 作物方块
     * @return 生长阶段的方块状态
     */
    private BlockState getGrowthStageBlockState(BlockState blockState, Block cropBlock) {
        // 查找 AGE 属性并动态设置生长阶段
        for (Property<?> property : blockState.getProperties()) {
            if (property.getName().equals("age")) {
                // 安全地检查并处理 Integer 类型的属性
                if (property.getValueClass() == Integer.class) {
                    @SuppressWarnings("unchecked")
                    Property<Integer> intProperty = (Property<Integer>) property;
                    int maxAge = Collections.max(intProperty.getPossibleValues());
                    int currentAge = Math.min(growthStage * maxAge / MAX_GROWTH_STAGES, maxAge);
                    return blockState.setValue(intProperty, currentAge);
                }
                break;
            }
        }
        return blockState;
    }

    /**
     * 更新生长阶段
     */
    private void updateGrowthStage() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastStageChange > STAGE_DURATION) {
            growthStage = (growthStage + 1) % MAX_GROWTH_STAGES;
            lastStageChange = currentTime;
        }
    }

    // ==================== 生物蛋相关方法 ====================

    /**
     * 为生物蛋创建实体
     * @return 实体对象
     */
    private Entity createEntityForSpawnEgg() {
        if (itemStack.getItem() instanceof SpawnEggItem spawnEgg) {
            try {
                EntityType<?> entityType = spawnEgg.getType(null);
                Entity entity = null;
                if (Minecraft.getInstance().level != null) {
                    entity = entityType.create(Minecraft.getInstance().level);
                }
                if (entity != null) {
                    entity.tickCount = 0;
                    return entity;
                }
            } catch (Exception e) {
                // 忽略异常
            }
        }
        return null;
    }

    // ==================== 输入处理方法 ====================

    @Override
    public boolean mouseScrolled(double mouseX, double mouseY, double delta) {
        if (delta > 0) {
            this.scaleFactor = Math.min(this.scaleFactor + SCALE_INCREMENT, MAX_SCALE);
        } else if (delta < 0) {
            this.scaleFactor = Math.max(this.scaleFactor - SCALE_INCREMENT, MIN_SCALE);
        }
        return true;
    }

    @Override
    public boolean mouseDragged(double mouseX, double mouseY, int button, double dragX, double dragY) {
        if (button == 0) { // 左键拖拽旋转
            float deltaX = (float)(mouseX - lastMouseX);
            float deltaY = (float)(mouseY - lastMouseY);

            rotationY = lastRotationY + deltaX * 0.5f;
            rotationX = lastRotationX + deltaY * 0.5f;
            return true;
        }
        return super.mouseDragged(mouseX, mouseY, button, dragX, dragY);
    }

    @Override
    public boolean mouseClicked(double mouseX, double mouseY, int button) {
        if (button == 0) { // 左键按下
            this.isDragging = true;
            this.lastMouseX = (int)mouseX;
            this.lastMouseY = (int)mouseY;
            this.lastRotationX = rotationX;
            this.lastRotationY = rotationY;
            return true;
        }
        return super.mouseClicked(mouseX, mouseY, button);
    }

    @Override
    public boolean mouseReleased(double mouseX, double mouseY, int button) {
        if (button == 0) { // 左键释放
            this.isDragging = false;
            this.lastRotationX = rotationX;
            this.lastRotationY = rotationY;
            return true;
        }
        return super.mouseReleased(mouseX, mouseY, button);
    }

    // ==================== 其他方法 ====================

    @Override
    public boolean isPauseScreen() {
        return false;
    }

    public boolean isSeed() {
        return isSeed;
    }
}